package sf.ext.gen;

import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import sf.database.template.enjoy.EnjoyHelp;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class GenUtils {

    private static String srcPathRelativeToSrc = "/main/java";
    private static String resourcePathRelativeToSrc = "/main/resources";

    public static String getJavaSRCPath() {
        return getPath(srcPathRelativeToSrc);
    }

    public static String getJavaResourcePath() {
        return getPath(resourcePathRelativeToSrc);
    }

    /**
     * 设置java代码生成根路径（影响pojo、mapper的生成）
     * @param srcPathRelativeToSrc 基于src目录的相对路径
     */
    public static void setSrcPathRelativeToSrc(String srcPathRelativeToSrc) {
        GenUtils.srcPathRelativeToSrc = srcPathRelativeToSrc;
    }

    /**
     * 设置资源文件生成根路径（影响md的生成）
     * @param resourcePathRelativeToSrc 基于src目录的相对路径
     */
    public static void setResourcePathRelativeToSrc(String resourcePathRelativeToSrc) {
        GenUtils.resourcePathRelativeToSrc = resourcePathRelativeToSrc;
    }

    public static String getPath(String relativeToSrc) {
        String srcPath;
        String userDir = System.getProperty("user.dir");
        if (userDir == null) {
            throw new NullPointerException("用户目录未找到");
        }
        File src = new File(userDir, "src");
        File resSrc = new File(src.toString(), relativeToSrc);
        if (resSrc.exists()) {
            srcPath = resSrc.toString();
        } else {
            srcPath = src.toString();
        }
        return srcPath;
    }

    /**
     * mapper 代码生成
     * @param classPath
     * @since 2.6.1
     */

    public static String getTemplate(String classPath) {
        InputStreamReader reader = null;
        try {
            //系统提供一个pojo模板
            InputStream ins = GenUtils.class.getResourceAsStream(classPath);
            reader = new InputStreamReader(ins, StandardCharsets.UTF_8);
            StringBuilder sb = new StringBuilder();
            int tmp;
            while ((tmp = reader.read()) != -1) {
                sb.append((char) tmp);
            }
            return sb.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static String renderByEnjoy(Map<String, Object> map, String content) {
        Engine engine = EnjoyHelp.getEnjoyEngine();
        Template template = engine.getTemplateByString(content);
        return template.renderToString(map);
    }

    public static void saveSourceFile(String srcPath, String pkg, String className, String content) {
        String file = srcPath + File.separator + pkg.replace('.', File.separatorChar);
        File f = new File(file);
        if (!f.exists()) {
            boolean succ = f.mkdirs();
            if (!succ) {
                throw new RuntimeException("创建文件夹失败 " + f);
            }
        }
        File target = new File(file, className + ".java");
        FileWriter writer = null;
        try {
            writer = new FileWriter(target);
            writer.write(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
